package com.blb.demo3;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * UDP客户端
 */
public class UDPClient {

    public void sendMessage(String ip,int port,String message){
        try {
            //创建客户端socket
            DatagramSocket socket = new DatagramSocket();
            //创建数据报，将数据包装进去，同时指定ip和端口
            byte[] data = message.getBytes();
            DatagramPacket packet = new DatagramPacket(
                    data,0,data.length,
                    InetAddress.getByName(ip),port);
            //发送数据包
            socket.send(packet);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new UDPClient().sendMessage("192.168.1.100",8888,"Hello 我是UDP");
    }
}
